package com.class5.springboot.frame.repo.real.init;

import java.sql.ResultSet;


import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;

import com.class5.springboot.frame.repo.tool.xml.DbTableColumn;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowMapper;

public class DbTableAdapter {
    private JdbcTemplate jt;
    private String name;
    private List<DbTableColumn> ls = null;
    private String schema;

    public DbTableAdapter(String schema, String name, JdbcTemplate jt) {
        this.name = name;
        this.jt = jt;
        this.schema =schema;
    }

    public String getName() {
        return name;
    }

    public synchronized List<DbTableColumn> getColumns(){
        if(ls != null) {
            return ls;
        }
        ls = jt.query("select * from information_schema.columns where TABLE_SCHEMA='"+schema+"' and TABLE_NAME = '"+name+"'", new RowMapper<DbTableColumn>() {
            @Override
            public DbTableColumn mapRow(ResultSet rs, int rowNum) throws SQLException {
                DbTableColumn dc = new DbTableColumn();
                dc.setColumnType(rs.getString("COLUMN_TYPE").toLowerCase());
                dc.setName(rs.getString("COLUMN_NAME").toLowerCase());
                dc.setComment(rs.getString("COLUMN_COMMENT"));
                dc.setDefaultValue(rs.getString("COLUMN_DEFAULT"));
                dc.setExtra(rs.getString("EXTRA"));
                dc.setIdentity("PRI".equalsIgnoreCase(rs.getString("column_key")));
                dc.setNullable("YES".equalsIgnoreCase(rs.getString("IS_NULLABLE")));
                return dc;
            }
        });
        return ls;
    }

    public boolean exists(String name) {
        for(DbTableColumn c : getColumns()) {
            if(c.getName().equalsIgnoreCase(name)) {
                return true;
            }
        }
        return false;
    }

    public DbTableColumn getColumn(String name) {
        for(DbTableColumn c : getColumns()) {
            if(c.getName().equalsIgnoreCase(name)) {
                return c;
            }
        }
        return null;
    }

}